<?php
namespace Swiftx\Component\Orm;
use Swiftx\Interfaces\Orm\Factory as FactoryInterface;
use Swiftx\Bundle\WeChat\System\Bundle;
use Swiftx\Interfaces\Orm\Entity;
use Swiftx\Interfaces\Orm\Manager;
use Swiftx\Interfaces\Orm\Query;
use \ErrorException;

/**
 * 工厂基础类
 */
class Factory implements FactoryInterface {

    /**
     * 实体管理器
     * @var Manager
     */
    protected $entityManager;

    /**
     * 实体模型类
     * @var string
     */
    protected $entityClass;

    /**
     * 实体管理器
     * @var Bundle
     */
    protected $bundle;

    /**
     * 注入实体管理器
     * @param Manager $manager
     * @auto-injection
     */
    public function setEntityManager(Manager $manager){
        $this->entityManager = $manager;
    }

    /**
     * 注入当前实体对象
     * @param Bundle $bundle
     * @auto-injection
     */
    public function setBundle(Bundle $bundle){
        $this->bundle = $bundle;
    }

    /**
     * 设置实体类型
     * @param string $class
     */
    public function setEntityClass(string $class){
        $this->entityClass = $class;
    }

    /**
     * 获取实体类名
     * @return string
     * @throws ErrorException
     */
    public function getEntityClass():string {
        if(!class_exists($this->entityClass))
            throw new ErrorException('模型不存在：'.$this->entityClass);
        return $this->entityClass;
    }

    /**
     * 获取查询器
     * @param string $name
     * @return Query
     */
    public function query(string $name):Query{
        return $this->entityManager->query(
            $this->entityClass, $name
        );
    }

    /**
     * 获取对象
     * @param array ...$args
     * @return Entity
     */
    public function fetch(... $args):?Entity {
        $params = array_merge([$this->entityClass],$args);
        return call_user_func_array([$this->entityManager, 'fetch'], $params);
    }

}